package com.realphim.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.realphim.app.model.ModelPhim;
import com.realphim.app.util.MyCache;

public class FragmentFeature extends Fragment {

    private RelativeLayout rlContent;

    private TextView tvTitle, tvTitleTranslate;

    private ProgressBar pbLoad;

    private int page;

    private ModelPhim currentPhim;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        page = getArguments().getInt("page");
        currentPhim = MyCache.getInstance().listPhimFeature.get(page);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_feature, null);
        rlContent = (RelativeLayout) view.findViewById(R.id.rlContent);
        pbLoad = (ProgressBar) view.findViewById(R.id.pbload);

        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        tvTitleTranslate = (TextView) view.findViewById(R.id.tvTitleTranslate);

        tvTitle.setText(currentPhim.title);
        tvTitleTranslate.setText(currentPhim.titleTranslate);

        if (currentPhim.imageBitmap == null) {
            new AsyncTaskLoadImage()
                    .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        } else {
            pbLoad.setVisibility(View.GONE);
            rlContent.setBackground(new BitmapDrawable(getActivity()
                    .getResources(), currentPhim.imageBitmap));
        }

        rlContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                MyCache.getInstance().currentPhim = currentPhim;
                Intent i = new Intent(getActivity(), ActivityDetailsPhim.class);
                startActivity(i);
                getActivity().overridePendingTransition(R.anim.slide_in_left,
                        R.anim.slide_out_left);
            }
        });

        return view;
    }

    private class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            InputStream iStream = null;
            URL url;
            try {
                url = new URL(currentPhim.imageUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = getActivity().getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
                        + page + "_feature.png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                // Config option bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;

                options.inSampleSize = 2;
                options.inPurgeable = true;
                options.inInputShareable = true;
                options.inJustDecodeBounds = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;

                Bitmap b = BitmapFactory.decodeStream(iStream, null, options);
                b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);

                // Bitmap result = Bitmap.createScaledBitmap(b, b.getWidth(),
                // b.getHeight(), true);
                // fOutStream.flush();
                // fOutStream.close();
                // b.recycle();
                return b;

            } catch (Exception e) {
                Log.e("LoadImage", e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            pbLoad.setVisibility(View.GONE);
            if (result != null) {
                currentPhim.imageBitmap = result;
                rlContent.setBackground(new BitmapDrawable(getActivity()
                        .getResources(), result));
            }
        }

    }
}
